import 'dart:io';

import 'package:ati_package/core/extension/ati_widgets_extension.dart';
import 'package:ati_package/core/utils/ati_color.dart';
import 'package:ati_package/pages/common/ati_scaffold.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

class TrendPublishView extends StatefulWidget {
  const TrendPublishView({super.key});

  @override
  State<TrendPublishView> createState() => _TrendPublishViewState();
}

class _TrendPublishViewState extends State<TrendPublishView> {
  final TextEditingController _textController = TextEditingController();
  final List<XFile> _images = [];
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImages() async {
    if (_images.length >= 9) return;

    final picked = await _picker.pickMultiImage(imageQuality: 85);
    if (picked.isNotEmpty) {
      final remaining = 9 - _images.length;
      setState(() {
        _images.addAll(picked.take(remaining));
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      _images.removeAt(index);
    });
  }

  void _submitPost() {
    final text = _textController.text.trim();
    if (text.isEmpty && _images.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请填写内容或选择图片')));
      return;
    }

    // TODO: 上传逻辑
    debugPrint('内容: $text');
    debugPrint('图片数量: ${_images.length}');
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('发布成功！')));

    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    // final canSubmit =
    //     _textController.text.trim().isNotEmpty || _images.isNotEmpty;

    return AtiScaffold(
      actionWidget:
          Container(
            width: 50.r,
            height: 25.r,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: AtiColor.primary,
              borderRadius: BorderRadius.circular(12.5.r),
            ),
            child: Text('发表', style: TextStyle(color: AtiColor.textHLColor1)),
          ).addTapGesture(
            onTap: () {
              _submitPost();
            },
          ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(12),
        child: Container(
          padding: const EdgeInsets.all(14),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              /// 文本输入框
              TextField(
                controller: _textController,
                maxLines: null,
                decoration: const InputDecoration(
                  hintText: '分享这一刻的想法…',
                  border: InputBorder.none,
                ),
                onChanged: (_) => setState(() {}),
              ),
              const SizedBox(height: 12),

              /// 图片区域
              _buildImageGrid(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildImageGrid() {
    final showAddButton = _images.length < 9;
    final allItems = [
      ..._images.map((x) => _buildImageItem(x)),
      if (showAddButton) _buildAddButton(),
    ];

    return Wrap(spacing: 10, runSpacing: 10, children: allItems);
  }

  Widget _buildImageItem(XFile file) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.file(
            File(file.path),
            width: 90,
            height: 90,
            fit: BoxFit.cover,
          ),
        ),
        Positioned(
          top: 4,
          right: 4,
          child: GestureDetector(
            onTap: () => _removeImage(_images.indexOf(file)),
            child: Container(
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black54,
              ),
              padding: const EdgeInsets.all(2),
              child: const Icon(Icons.close, size: 16, color: Colors.white),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAddButton() {
    return GestureDetector(
      onTap: _pickImages,
      child: Container(
        width: 90,
        height: 90,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey[300]!),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Icon(Icons.add, color: Colors.grey, size: 28),
      ),
    );
  }
}
